package admin

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go_auth/ext/app"
	"go_auth/ext/e"
	"go_auth/servers/admins"
	"go_auth/utils/commons"
	"net/http"
)

func UpdateAd(c *gin.Context) {
	var ad []admins.Ad
	var appG = app.Gin{C: c}
	err := c.ShouldBindJSON(&ad)
	code := e.Success

	if !commons.CheckErr(err) {
		code = e.ParamsError
	} else if !admins.UpdateAd(ad) {
		code = e.UpdateError
	}
	appG.Response(http.StatusOK, code, nil)
}

func GetAllAd(c *gin.Context) {
	var appG = app.Gin{C: c}
	var ads []admins.Ad
	ad, code := admins.GetAllAd()
	err := json.Unmarshal(ad, &ads)
	if !commons.CheckErr(err) {
		appG.Response(http.StatusOK, e.JsonToBytes, nil)
		return
	}
	appG.Response(http.StatusOK, code, ads)
}

func Add(c *gin.Context) {
	var appG = app.Gin{C: c}
	url := c.PostForm("url")
	name := c.PostForm("name")
	period := c.PostForm("period")
	rank := c.PostForm("rank")
	status := c.PostForm("status")
	ads := admins.Ad{}
	ads.Url = url
	ads.Name = name
	ads.Period, _ = commons.StrToInt(period)
	ads.Status, _ = commons.StrToInt(status)
	ads.Rank, _ = commons.StrToInt(rank)
	code := ads.Add()
	appG.Response(http.StatusOK, code, ads)
}
